

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言pytest是python新流行的自动化测试框架, 相比于老牌的 Unittest, pytest更加简洁, 效率更高, 并且目前来说, pytest的使用率要比unitest更高. 此外, pytest还具备很多十分方便的插件, 帮助我们快速完成某些实用场景场景, 比如:  生成报告 跳过用例 顺序执行 数据驱动 用例标记  pytest具备以下特点:  1.非常容易上手，入门简单，文档丰富">
<meta property="og:type" content="article">
<meta property="og:title" content="pytest基本使用">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2023/05/10/autoTest/pytest%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言pytest是python新流行的自动化测试框架, 相比于老牌的 Unittest, pytest更加简洁, 效率更高, 并且目前来说, pytest的使用率要比unitest更高. 此外, pytest还具备很多十分方便的插件, 帮助我们快速完成某些实用场景场景, 比如:  生成报告 跳过用例 顺序执行 数据驱动 用例标记  pytest具备以下特点:  1.非常容易上手，入门简单，文档丰富">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-05-10T02:08:59.000Z">
<meta property="article:modified_time" content="2023-09-01T06:48:21.138Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="自动化测试">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="自动化测试框架">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>pytest基本使用 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="pytest基本使用"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-05-10 10:08" pubdate>
          2023年5月10日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          6.3k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">pytest基本使用</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年9月1日 下午
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>pytest是python新流行的自动化测试框架, 相比于老牌的 <strong>Unittest</strong>, pytest更加简洁, 效率更高, 并且目前来说, pytest的使用率要比unitest更高.</p>
<p>此外, pytest还具备很多十分方便的插件, 帮助我们快速完成某些实用场景场景, 比如:</p>
<ul>
<li>生成报告</li>
<li>跳过用例</li>
<li>顺序执行</li>
<li>数据驱动</li>
<li>用例标记</li>
</ul>
<p>pytest具备以下特点:</p>
<blockquote>
<p>1.非常容易上手，入门简单，文档丰富，文档中有很多实例可以参考<br>2.支持简单的单元测试和复杂的功能测试<br>3.支持参数化<br>4.执行测试过程中可以将某些测试跳过，或者对某些预期失败的Case标记成失败<br>5.支持重复执行失败的Case<br>6.支持运行由Unittest编写的测试Case<br>7.具有很多第三方插件，并且可以自定义扩展<br>8.方便的和持续集成工具集成</p>
</blockquote>
<p>pytest虽然很好用, 但是只是其他大佬封装出来的框架, 并不是python的标准库, 属于第三方库, 需要pip进行安装</p>
<blockquote>
<p>pip install pytest</p>
</blockquote>
<h1 id="pytest如何运行"><a href="#pytest如何运行" class="headerlink" title="pytest如何运行"></a>pytest如何运行</h1><p>写法其实和unittest类似, 默认情况下, 运行 <code>test</code> 开头的<strong>类/类方法/函数</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># filename: test3.py</span><br><span class="hljs-keyword">import</span> pytest <span class="hljs-comment"># 引入pytest包</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(): <span class="hljs-comment"># test开头的测试函数</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_a&quot;</span>)<br>    <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言成功</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_b&quot;</span>)<br>    <span class="hljs-keyword">assert</span> <span class="hljs-number">0</span> <span class="hljs-comment"># 断言失败</span><br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;test3.py&#x27;</span>]) <span class="hljs-comment"># 调用pytest的main函数执行测试</span><br>    <span class="hljs-comment"># pytest.main([&#x27;-s&#x27;, __file__]) # 通过 __file__ 获取脚本文件路径</span><br></code></pre></td></tr></table></figure>

<p>这种运行方式, 是直接导入的pytest, 通过 <code>pytest.main</code> 来运行</p>
<p>参数为一个数组, 数组的每个元素就是一个命令行参数</p>
<p>所以pytest也支持命令行直接运行, 如上述例子: <code>pytest -s test3.py</code></p>
<p>所以, pyest也是可以通过命令行的方式, 来 <strong>指定运行某个用例文件</strong></p>
<h1 id="Pytest的setup和teardown函数"><a href="#Pytest的setup和teardown函数" class="headerlink" title="Pytest的setup和teardown函数"></a>Pytest的setup和teardown函数</h1><p>用过unittest的同学应该知道这两个函数, 没用过的我给解释一下.</p>
<p>就是前置动作/后置动作</p>
<p>换句话说, 就是每一条用例/步骤, 执行前后会执行的动作.</p>
<p>pytest中的setup和teardown主要分为：模块级，类级，方法级，函数级。</p>
<h2 id="函数级别"><a href="#函数级别" class="headerlink" title="函数级别"></a>函数级别</h2><p>setup_function/teardown_function，在每个测试函数前后运行，只对函数用例生效</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># filename: test3.py</span><br><span class="hljs-keyword">import</span> pytest <span class="hljs-comment"># 引入pytest包</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">setup_function</span>():  <span class="hljs-comment"># 在每个函数用例运行前会执行的函数, 函数名固定</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;----------------------before execute&quot;</span>)<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">teardown_function</span>():  <span class="hljs-comment"># 在每个函数用例运行后会执行的函数, 函数名固定</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;----------------------after execute&quot;</span>)<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(): <span class="hljs-comment"># test开头的测试函数</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_a&quot;</span>)<br>    <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言成功</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_b&quot;</span>)<br>    <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言失败</span><br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;test3.py&#x27;</span>]) <span class="hljs-comment"># 调用pytest的main函数执行测试</span><br>    <span class="hljs-comment"># pytest.main([&#x27;-s&#x27;, __file__]) # 通过 __file__ 获取脚本文件路径</span><br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">结果:</span><br><span class="hljs-string">collected 2 items</span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py ----------------------before execute</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">.----------------------after execute</span><br><span class="hljs-string">----------------------before execute</span><br><span class="hljs-string">-------&gt;test_b</span><br><span class="hljs-string">.----------------------after execute</span><br><span class="hljs-string"></span><br><span class="hljs-string"></span><br><span class="hljs-string">============================== 2 passed in 0.02s ==============================</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>通过结果可以看得出来, 每次运行一个函数用例时, 都会运行 <strong>setup_function/teardown_function</strong></p>
<h2 id="模块级别"><a href="#模块级别" class="headerlink" title="模块级别"></a>模块级别</h2><p>可以把模块理解成一个 py文件</p>
<p>setup_module/teardown_module，对整个.py文件生效，文件内所有用例运行前后执行</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># filename: test3.py</span><br><span class="hljs-keyword">import</span> pytest <span class="hljs-comment"># 引入pytest包</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">setup_module</span>():  <span class="hljs-comment"># 在整个py文件运行前会执行的函数, 函数名固定</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;----------------------before execute&quot;</span>)<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">teardown_module</span>():  <span class="hljs-comment"># 在整个py文件用例运行后会执行的函数, 函数名固定</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;----------------------after execute&quot;</span>)<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(): <span class="hljs-comment"># test开头的测试函数</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_a&quot;</span>)<br>    <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言成功</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_b&quot;</span>)<br>    <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言失败</span><br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;test3.py&#x27;</span>]) <span class="hljs-comment"># 调用pytest的main函数执行测试</span><br>    <span class="hljs-comment"># pytest.main([&#x27;-s&#x27;, __file__]) # 通过 __file__ 获取脚本文件路径</span><br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">结果:</span><br><span class="hljs-string">collected 2 items</span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py ----------------------before execute</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">.-------&gt;test_b</span><br><span class="hljs-string">.----------------------after execute</span><br><span class="hljs-string"></span><br><span class="hljs-string"></span><br><span class="hljs-string">============================== 2 passed in 0.02s ==============================</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>通过结果可以看得出来, 运行这个py文件时, 只会运行一次 <strong>setup_module/teardown_module</strong></p>
<h2 id="方法级别"><a href="#方法级别" class="headerlink" title="方法级别"></a>方法级别</h2><p>运行于测试类的测试方法的始末，即运行一次测试方法会运行一次setup_method和teardown_method</p>
<p>测试类, 如果是用过unittest的同学应该不模式, 这里我通过例子介绍一下什么是测试类.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># filename: test3.py</span><br><span class="hljs-keyword">import</span> pytest <span class="hljs-comment"># 引入pytest包</span><br><br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():  <span class="hljs-comment"># Test开头的, 就是测试类, pytest会检测到测试类, 并运行其下的所有 test 开头的 方法</span><br><br>    <span class="hljs-comment"># 因为是类方法, 所以都要加上self, 否则会报错</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">setup_method</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 每个类方法函数执行前会运行的函数, 函数名固定</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;----------------------before execute&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">teardown_method</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 每个类方法函数执行后会运行的函数, 函数名固定</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;----------------------after execute&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>): <span class="hljs-comment"># test开头的测试函数</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_a&quot;</span>)<br>        <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言成功</span><br><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_b&quot;</span>)<br>        <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言失败</span><br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;test3.py&#x27;</span>]) <span class="hljs-comment"># 调用pytest的main函数执行测试</span><br>    <span class="hljs-comment"># pytest.main([&#x27;-s&#x27;, __file__]) # 通过 __file__ 获取脚本文件路径</span><br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">结果:</span><br><span class="hljs-string">collected 2 items</span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py ----------------------before execute</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">.----------------------after execute</span><br><span class="hljs-string">----------------------before execute</span><br><span class="hljs-string">-------&gt;test_b</span><br><span class="hljs-string">.----------------------after execute</span><br><span class="hljs-string"></span><br><span class="hljs-string"></span><br><span class="hljs-string">============================== 2 passed in 0.02s ==============================</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>通过结果可以看得出来, 每次运行一个类方法用例时, 都会运行 <strong>setup_method/teardown_method</strong></p>
<h2 id="类级别"><a href="#类级别" class="headerlink" title="类级别"></a>类级别</h2><p>类级别实际上和模块级别差不多</p>
<p>只不过把这个对象从文件换成了类</p>
<p>运行于测试类的始末，即:在一个测试内只运行一次setup_class和teardown_class</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># filename: test3.py</span><br><span class="hljs-keyword">import</span> pytest <span class="hljs-comment"># 引入pytest包</span><br><br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():  <span class="hljs-comment"># Test开头的, 就是测试类, pytest会检测到测试类, 并运行其下的所有 test 开头的 方法</span><br><br>    <span class="hljs-comment"># 因为是类方法, 所以都要加上self, 否则会报错</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">setup_class</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 整个测试类执行前会运行的函数, 函数名固定</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;----------------------before execute&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">teardown_class</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 整个测试类执行后会运行的函数, 函数名固定</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;----------------------after execute&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>): <span class="hljs-comment"># test开头的测试函数</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_a&quot;</span>)<br>        <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言成功</span><br><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-------&gt;test_b&quot;</span>)<br>        <span class="hljs-keyword">assert</span> <span class="hljs-number">1</span> <span class="hljs-comment"># 断言失败</span><br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;test3.py&#x27;</span>]) <span class="hljs-comment"># 调用pytest的main函数执行测试</span><br>    <span class="hljs-comment"># pytest.main([&#x27;-s&#x27;, __file__]) # 通过 __file__ 获取脚本文件路径</span><br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">结果:</span><br><span class="hljs-string">collected 2 items</span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py ----------------------before execute</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">.-------&gt;test_b</span><br><span class="hljs-string">.----------------------after execute</span><br><span class="hljs-string"></span><br><span class="hljs-string"></span><br><span class="hljs-string">============================== 2 passed in 0.02s ==============================</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>通过结果可以看得出来, 运行这个测试类时, 只会运行一次 <strong>setup_class/teardown_class</strong></p>
<h1 id="执行运行"><a href="#执行运行" class="headerlink" title="执行运行"></a>执行运行</h1><p>之前说过, 通过命令行, 可以实现指定运行某个用例文件</p>
<p>实际上, pytest的指定深度比想象中的更加细致</p>
<p>可以支持:</p>
<ul>
<li>指定文件</li>
<li>指定函数</li>
<li>指定测试类</li>
<li>指定类方法 </li>
<li>指定文件夹</li>
</ul>
<h2 id="指定文件"><a href="#指定文件" class="headerlink" title="指定文件"></a>指定文件</h2><blockquote>
<p>pytest -s xxx/xxx.py</p>
</blockquote>
<h2 id="指定函数"><a href="#指定函数" class="headerlink" title="指定函数"></a>指定函数</h2><blockquote>
<p>pytest -s xxx/xxx.py::函数名<br>如: pytest -s test3.py::test_a</p>
</blockquote>
<h2 id="指定测试类"><a href="#指定测试类" class="headerlink" title="指定测试类"></a>指定测试类</h2><blockquote>
<p>pytest -s xxx/xxx.py::类名<br>如: pytest -s test3.py::TestCase</p>
</blockquote>
<h2 id="指定类方法"><a href="#指定类方法" class="headerlink" title="指定类方法"></a>指定类方法</h2><blockquote>
<p>pytest -s xxx/xxx.py::类名::类方法名<br>如: pytest -s test3.py::TestCase::test_a</p>
</blockquote>
<h2 id="指定文件夹"><a href="#指定文件夹" class="headerlink" title="指定文件夹"></a>指定文件夹</h2><p>首先, 我们在根目录中新建一个文件夹: testcase</p>
<p>在 testcase 中, 我们新建三个py文件</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sh">├─ testcase<br>│  ├─ abc.py<br>│  ├─ test_1.py<br>│  ├─ test_2.py<br></code></pre></td></tr></table></figure>

<p>每个py文件中, 写入:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_1</span>():<br>    <span class="hljs-built_in">print</span>(__file__, <span class="hljs-string">&quot;done&quot;</span>)<br></code></pre></td></tr></table></figure>

<p>运行命令名命名: pytest -s ./testcase</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">collected 2 items                                                                                                                                                                                                                  </span><br><span class="hljs-string"></span><br><span class="hljs-string">testcase\test_1.py E:\Users\w210115\Desktop\test\testcase\test_1.py done</span><br><span class="hljs-string">.</span><br><span class="hljs-string">testcase\test_2.py E:\Users\w210115\Desktop\test\testcase\test_2.py done</span><br><span class="hljs-string">.</span><br><span class="hljs-string"></span><br><span class="hljs-string">======================================================================================================= 2 passed in 0.04s</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>pytest会运行指定文件夹下的所有以 <code>test_</code> 开头的文件</p>
<p>并且, 如果该文件夹下还有 <strong>子文件夹</strong>, 会继续递归查找, 找出所有的 <code>test_</code> 开头的文件并运行</p>
<p>通过上述结果来看, <code>abc.py</code> 文件并没有被运行, 这是正确的.</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>我们可以通过pytest的运行规则, 得出一个规范:</p>
<ul>
<li>测试类必须<strong>Test</strong>开头</li>
<li>测试函数/方法/文件, 必须**test_**开头</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/" class="category-chain-item">自动化测试</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/pytest/" class="category-chain-item">pytest</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/">#自动化测试</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95%E6%A1%86%E6%9E%B6/">#自动化测试框架</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>pytest基本使用</div>
      <div>https://walker_kwu.gitee.io/my-blog/2023/05/10/autoTest/pytest基本使用/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年5月10日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年9月1日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2023/05/10/autoTest/pytest%E5%B8%B8%E7%94%A8%E6%8F%92%E4%BB%B6/" title="pytest常用插件">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">pytest常用插件</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2023/03/25/python/base/python%E5%B8%B8%E7%94%A8%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%93/" title="python常用第三方库">
                        <span class="hidden-mobile">python常用第三方库</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
